﻿using SIR.DAL;
using System.ServiceProcess;
using System.Threading;

namespace SIR.Services.ImageProcessing
{
	partial class Service : ServiceBase
	{
		public Service()
		{
			InitializeComponent();
			// Set up the timers
			_sleepTimer = new Timer(SleepTimerCallback, null, Timeout.Infinite, Timeout.Infinite);
			_cleanUpTimer = new Timer(FixTimerCallback, null, 10000, Timeout.Infinite);
		}

		private readonly Timer _sleepTimer = null;
		private readonly Timer _cleanUpTimer = null;

		protected override void OnStart(string[] args)
		{
			try
			{
				// Connect to the database
				DAL.DataServer.Connect(System.Configuration.ConfigurationManager.ConnectionStrings["SIR"].ConnectionString);
				// Start the service in "sleep" mode
				Sleep();
			}
			catch (System.Exception ex)
			{
				// Temporary to log the error
				System.IO.File.WriteAllLines(@"C:\temp\error.txt", new[] {
					System.Configuration.ConfigurationManager.ConnectionStrings["SIR"].ConnectionString,
					ex.Message});
				throw;
			}
		}

		protected override void OnStop()
		{
			// Disconnect from the DB
			DataServer.Disconnect();
			// Stop the sleep timer
			_sleepTimer.Change(Timeout.Infinite, Timeout.Infinite);
		}

		private void FixTimerCallback(object state)
		{
			// Fix items that failed during the processing threads
			ImageProcessing.Processing.FixedFailedQueueItems();
			// Set the clean up to happen again in 10 seconds
			_cleanUpTimer.Change(10000, Timeout.Infinite);
		}

		private void SleepTimerCallback(object state)
		{
			// Service back awake, try to process the queue
			Next();
		}

		private void Next()
		{
			// Continue processing the queue while there are images waiting to be processed
			while (Processing.ProcessNextImage()) { }
			// No more images so sleep
			Sleep();
		}

		private void Sleep()
		{
			// Sleep the processing thread for 10 seconds
			_sleepTimer.Change(10000, Timeout.Infinite);
		}
	}
}
